
using System;
using System.Collections.Generic;
using System.Data;

namespace Common
{
	/// <summary>
	/// Description of PageDao.
	/// </summary>
	public class PageQueryDao
	{
		private PageQueryDao()
		{
		}
		public static Page getProducts(int curPageIndex)
		{
			return getProducts(curPageIndex,null);
		}
		public static Page getProducts(int curPageIndex,Product condition)
		{
			string sqlQuery="select * from product";
			string sqlCount="select count(*) from product";
			string sqlOrder = " order by name";
			if(condition!=null)
			{
				string sqlCondition=" where price>"+condition.Price+" and quantity< "+condition.Quantity;
				sqlQuery +=sqlCondition+sqlOrder;
				sqlCount +=sqlCondition;
			}
			int totalRecord = AccessDBUtil.ExecuteScalar(sqlCount);
			Page page = new Page(totalRecord,AccessPageUtil.PAGE_SIZE);
			if(curPageIndex>=page.TotalPage)curPageIndex=page.TotalPage-1;
			if(curPageIndex<0)curPageIndex=0;
			page.CurPageIndex=curPageIndex;
			
			DataSet data = AccessPageUtil.query(sqlQuery,curPageIndex,totalRecord);
			List<Product> ls = new List<Product>();
			foreach(DataRow row in data.Tables["ds"].Rows)
			{
				ls.Add(Row2Product(row));
			}
			page.ValueList=ls;
			return  page;
		}
		private static Product Row2Product(DataRow row)
		{
			Product product = new Product();
			product.Id = Int32.Parse(row["id"].ToString());
			product.Name = row["name"].ToString();
			product.Quantity = Int32.Parse(row["quantity"].ToString());
			product.Price = Double.Parse(row["price"].ToString());
			product.SaleDate = DateTime.Parse(row["sale_date"].ToString());
			product.CheckedFlag = Boolean.Parse(row["checked_flag"].ToString());
			return product;
		}
	}
}
